<template>
  <view class="container p-bottom bs-checkout">
    <!-- 配送地址 -->
    <view v-if="need_address">
      <view v-if="address && address.address_id" @tap.stop.prevent="selectAddress">
        <view class="b-f">
          <view class="flow-checkout-header">
            <text class="iconfont icon-dingwei"></text>
            <view class="flow-header-left">
              <view class="flow-checkout-admin f-30 col-3">
                <text>{{ address.name }}</text>
                <text>{{ address.phone }}</text>
                <text class="col-m"></text>
              </view>
              <view class="flow-checkout-address f-28">
                {{ address.province }}/{{ address.city }}/{{ address.area }}/{{ address.detail }}
              </view>
            </view>
            <view class="flow-header-right pr-12">
              <text class="iconfont icon-xiangyoujiantou user-orderJtou"></text>
            </view>
          </view>
        </view>
      </view>
      <view v-else>
        <view class="flow-checkout-header" @tap.stop.prevent="gotoPath('/pages/packageA/address/index?from=checkout')">
          <text class="iconfont icon-dingwei"></text>
          <view class="flow-header-left">
            <view class="f-28 col-6">去选择配送地址</view>
          </view>
          <view class="flow-header-right p-r15">
            <text class="iconfont icon-xiangyoujiantou user-orderJtou"></text>
          </view>
        </view>
      </view>

    </view>

    <!-- 商品列表 -->
    <view class="m-top20">
      <view class="checkout_list" v-for="(item, index) in goods_list" :key="index">
        <navigator :url="'/pages/goods/detail?item_id=' + item.goods_id">
          <view class="dis-flex flow-shopList" :data-index="index">
            <view class="flow-list-left">
              <image mode="scaleToFill" :src="item.goods_image"></image>
            </view>
            <view class="flow-list-right">
              <text class="f-30 col-3 twolist-hidden">{{ item.goods_name }}</text>
              <text
                  class="f-26 col-7">{{ item.spec_name ? item.spec_name : '' }}
              </text>
              <view class="flow-list-cont">
                <text class="flow-cont">￥{{ item.goods_price }}</text>
                <text class="small">×{{ item.total_num }}</text>
                <!--                <view class="zhekou" v-if="item.level != null && item.vip > 0">
                                  会员折扣：{{ item.agio }}折,折后价{{ (item.goods_price * item.agio) / 10 }}
                                </view>-->
              </view>
            </view>
          </view>
        </navigator>
      </view>
      <view class="flow-num-box b-f padding-box">
        <text>共{{ order_total_num }}个商品，合计：</text>
        <text class="flow-money col-m">￥{{ order_total_price }}</text>
      </view>
    </view>

    <view class="flow-all-money b-f m-top20">
      <view class="ipt-wrapper dis-flex flow-all-list">
        <input @input="bindRemark" placeholder="选填：买家留言（100字以内）" :value="remark"/>
      </view>
    </view>

    <!-- 商品金额 -->
    <view class="flow-all-money b-f m-top20">
      <view class="dis-flex flow-all-list">
        <text class="flex-five">商品总金额:</text>
        <view class="flex-five t-r">
          <text class="col-m">￥{{ order_total_price }}</text>
        </view>
      </view>
      <view class="dis-flex flow-all-list">
        <text class="flex-five">优惠券：</text>
        <view class="flex-five t-r">
          <view class="" @tap.stop.prevent="togglePopupCoupon()">
            <view v-if="coupon_list.length > 0">
              <text class="col-m" v-if="selectCoupon.id">-￥{{ selectCoupon.reduce_price }}</text>
              <text class="col-m" v-else>有{{ coupon_list.length }}张优惠券可用</text>
              <text class="iconfont icon-xiangyoujiantou user-orderJtou"></text>
            </view>
            <text v-else class="">无优惠券可用</text>
          </view>
        </view>
      </view>
      <!--      <view v-if="address && address.level  && agio_count > 0" class="dis-flex flow-all-list">
              <text class="flex-five">会员省：</text>
              <view class="flex-five t-r">
                <text class="col-m">￥{{ agio_count }}</text>
              </view>
            </view>-->
      <view class="dis-flex flow-all-list" v-if="need_address">
        <text class="flex-five">配送费用：</text>
        <view class="flex-five t-r">
          <view v-if="address">
            <text class="col-m">+￥{{ shipping_fee }}</text>
          </view>
          <view v-else>
            <text class="col-7">请先选择配送地址</text>
          </view>
        </view>
      </view>
      <view class="dis-flex flow-all-list">
        <text class="flex-five">是否开票：</text>
        <view class="flex-five t-r">
          <switch @change="toggleInvoice" :checked="invoice"/>
        </view>
      </view>

    </view>

    <!-- 提交订单 -->
    <view class="flow-fixed-footer b-f m-top10" v-if="goods_list.length > 0">
      <view class="dis-flex chackout-box">
        <view class="chackout-left pl-12">
          实付款：
          <text class="col-m">￥{{ actual_pay_price > 0 ? actual_pay_price : order_pay_price }}</text>
        </view>
        <view @tap="paymentSelectorOpen" class="chackout-right">
          <text class="flow-btn f-32">提交订单</text>
        </view>
      </view>
    </view>


    <!-- 优惠券弹出框 -->
    <c_popup :show="showBottomPopup" type="bottom" @close="togglePopupCoupon">
      <view class="popup__coupon">
        <view class="coupon__title f-32">选择优惠券</view>
        <!-- 不使用优惠券 -->
        <view class="coupon__do_not dis-flex flex-y-center flex-x-center">
          <view class="control dis-flex flex-y-center flex-x-center" @tap.stop.prevent="doNotCouponTap">
            <text class="f-26">不使用优惠券</text>
          </view>
        </view>
        <!-- 优惠券列表 -->
        <view class="coupon-list">
          <scroll-view :scroll-y="true" style="height: 565rpx">
            <view class="coupon-item" v-for="(item, index) in coupon_list" :key="index">
              <view :class="'item-wrapper color__' + item.color.text" @tap.stop.prevent="selectCouponTap"
                    :data-index="index" :data-coupon-id="item.id">
                <view class="coupon-type">{{ item.coupon_type.text }}</view>
                <view class="tip dis-flex flex-dir-column flex-x-center">
                  <view v-if="item.coupon_type.value == 10">
                    <text class="f-30">￥</text>
                    <text class="money">{{ item.reduce_price }}</text>
                  </view>
                  <text class="money" v-if="item.coupon_type.value == 20">{{ item.discount }}折</text>
                  <text class="pay-line">满{{ item.min_price }}元可用</text>
                </view>
                <view class="split-line"></view>
                <view class="content dis-flex flex-dir-column flex-x-between">
                  <view class="title">{{ item.name }}</view>
                  <view class="bottom dis-flex flex-y-center">
                    <view class="time flex-box">
                      <text>有效期：{{ item.start_time.text }}~{{ item.end_time.text }}</text>
                    </view>
                    <!-- <view class="state flex-box">
                    <text>-￥{{ item.reduced_price }}</text>
                  </view> -->
                  </view>
                </view>
              </view>
            </view>
          </scroll-view>
        </view>
        <view class="footer-fixed f-32">
          <view @tap="togglePopupCoupon" class="order-bt" style="width: 100%">关闭</view>
        </view>
      </view>
    </c_popup>
    <c_payment :from="'order-checkout'" ref="paymentSelector" @payment-selected="onPaymentMethodChange"
               @confirm="submitOrder"></c_payment>
    <c_address_popup
        ref="addressPopup"
        :filteredList="address_list"
        :path="'/pages/packageA/address/index'"
        @selected="selectAddressOK"
        @closePopup="closeAddressPopup"
        show_type="list"
    >

    </c_address_popup>

    <c_invoice_popup
        ref="invoicePopup"
        :filteredList="invoice_list"
        :path="'/pages/packageA/invoice/index'"
        @selected="selectInvoiceOK"
        @close="closeInvoicePopup"
        show_type="list"
    >

    </c_invoice_popup>
  </view>
</template>

<script>
import c_popup from "@/components/popup/c_popup.vue";
import cart_api from "@/common/cart_api";
import order_api from "@/common/order_api";
import c_payment from "@/components/payment/c_payment.vue";
import c_address_popup from "@/components/address_popup/c_address_popup.vue";
import c_invoice_popup from "@/components/address_popup/c_invoice_popup.vue";
import address_api from "@/common/address_api";
import {list_options as invoice_list} from "@/common/invoice_api";

export default {
  components: {
    c_popup, c_payment, c_address_popup, c_invoice_popup
  },
  data() {
    return {
      need_address: true,
      invoice_id: 0,
      invoice: false,
      invoice_list: [],
      address_list: [],
      pay_way: '1',
      // 当前页面参数
      options: {},

      address: null,

      // 是否存在收货地址
      goods: {},

      // 商品信息

      // 选择的优惠券
      selectCoupon: {
        index: null,
        id: null,
        reduced_price: '0.00'
      },

      // 买家留言
      remark: '',

      // 禁用submit按钮
      disabled: false,
      error: '',
      showBottomPopup: false,
      actual_pay_price: '',
      address_id: '',
      detail: '',
      goods_list: [],
      shipping_fee: 0,
      order_total_num: 0,
      order_total_price: '',
      coupon_list: [],
      agio_count: 0,
      order_pay_price: '',
    };
  },
  watch: {
    invoice: function (newVal, oldVal) {
      if (newVal) {
        if (newVal) {
          this.getInvoiceList()
          this.$refs.invoicePopup.togglePopup();
        }
      } else {
        this.setData({
          invoice_id: 0
        })
      }
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 当前页面参数
    this.options = options;
    this.getInvoiceList()
    //console.log(options)
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 获取当前订单信息
    this.selectCoupon = {}
    this.actual_pay_price = '';
    this.getOrderData();
    this.getAddressList();
  },
  methods: {
    toggleInvoice() {
      this.invoice = !this.invoice
    },
    selectInvoiceOK(item) {
      this.setData({
        invoice_id: item.invoice_id
      })
    },
    getInvoiceList() {
      invoice_list({}).then(res => {
        if (res.code !== 0) {
          this.$u.toast(res.msg)
          return false
        }
        this.setData({
          invoice_list: res.data.list
        })
      })
    },



    closeAddressPopup() {
      this.$refs.addressPopup.closePopup();
    },
    selectAddressOK(item) {
      console.log(item);
      if (!item.address_id) {
        this.$u.toast('请选择收货地址');
        return;
      }
      this.setData({
        address: item
      })
      this.getOrderData()
    },
    getAddressList() {
      address_api.list({from: 'checkout'}).then(res => {
        if (res.code === 0) {
          this.setData({
            address_list: res.data.list
          })
        }

      })
    },
    onPaymentMethodChange(e) {

    },
    paymentSelectorOpen() {
      this.$refs.paymentSelector.openPopup();
    },
    /**
     * 获取当前订单信息
     */
    getOrderData: function () {
      let that = this;
      let options = that.options; // 获取订单信息回调方法

      // 立即购买
      if (options.order_type === 'buyNow') {
        cart_api.checkout({
          order_type: options.order_type,
          item_id: options.item_id,
          goods_num: options.goods_num,
          spec_id: options.spec_id || 0,
          invoice_id: that.invoice_id || 0,
          address_id: (that.address && that.address.address_id) || 0
        }).then(res => {
          if (res.code !== 0) {
            this.$u.toast(res.msg)
            return;
          }
          //console.log(res);
          that.setData(res.data);
        })

      } else if (options.order_type === 'cart') {
        cart_api.checkout({
          order_type: 'cart',
          cart_ids: options.cart_ids,
          invoice_id: that.invoice_id || 0,
          address_id: (that.address && that.address.address_id) || 0
        }).then(res => {
          if (res.code !== 0) {
            this.$u.toast(res.msg)
            return
          }
          that.setData(res.data);
        })

      }
    },

    /**
     * 选择收货地址
     */
    selectAddress: function () {
      this.$refs.addressPopup.togglePopup();
    },

    pay_order(res) {
      let that = this;
      //支付失败
      if (res.data.pay_status === -1) {
        that.$u.toast(res.msg)
        setTimeout(function () {
          // 跳转到未付款订单
          uni.redirectTo({
            url: '/pages/packageA/order/index'
          });
        }, 1500)
        return false;
      }
      if (that.pay_way == 1) {
        let param = res.data.param;
        // 发起微信支付(小程序)
        uni.requestPayment({
          timeStamp: param.timeStamp,
          nonceStr: param.nonceStr,
          package: 'prepay_id=' + param.prepay_id,
          signType: 'MD5',
          paySign: param.paySign,
          success: function (res) {
            // 跳转到订单详情
            uni.redirectTo({
              url: '/pages/packageA/order/detail?order_sn=' + res.data.order_sn
            });
          },
          fail: () => {
            that.show_msg('支付失败')
            setTimeout(function () {
              // 跳转到未付款订单
              uni.redirectTo({
                url: '/pages/packageA/order/index'
              });
            }, 1500)
          }
        });
      } else if (that.pay_way == 2) {
        //支付宝
        //#ifdef H5
        console.log(res.data.url)
        uni.navigateTo({
          url: '/pages/packageA/h5/web?bsfrom=order-pay&order_sn=' + res.data.order_sn + '&url=' + res.data.url,
          success: () => {
          },
          fail: (err) => {
            console.log(err)
          }
        })
        return;
        //#endif
        let order_sn = res.data.order_sn;
        //支付宝
        uni.requestPayment({
          provider: 'alipay',
          orderInfo: res.data.params,
          success: function (res) {
            // 跳转到订单详情
            uni.redirectTo({
              url: '/pages/packageA/order/detail?order_sn=' + order_sn
            });
          },
          fail: function (res) {
            that.show_msg('支付失败')
            setTimeout(function () {
              // 跳转到未付款订单
              uni.redirectTo({
                url: '/pages/packageA/order/index'
              });
            }, 1500)
          }
        });
      } else if (that.pay_way == 3) {
        that.$u.toast('订单已提交，请等待管理员审核')
        setTimeout(function () {
          uni.redirectTo({
            url: '/pages/packageA/order/detail?order_sn=' + res.data.order_sn
          });
        }, 2000)
      } else if (that.pay_way == 4) {
        that.$u.toast(res.msg)
        if (res.code === 0) {
          setTimeout(function () {
            // 跳转到订单列表
            uni.redirectTo({
              url: '/pages/packageA/order/index'
            });
          }, 1500)
        }
      }
    },

    /**
     * 订单提交
     */
    submitOrder: function (e) {
      console.log('confirmPay', e)
      this.pay_way = e.value
      if (!this.pay_way) {
        this.show_msg('请选择支付方式')
        return false
      }

      let that = this;
      let options = that.options;
      if (that.disabled) {
        return false;
      }
      if (that.need_address && !that.address) {
        this.show_msg('请选择收货地址')
        return false
      }
      if (that.invoice && that.invoice_id == 0) {
        this.show_msg('请选择发票')
        return false
      }

      // 按钮禁用, 防止二次提交
      that.disabled = true;

      // 显示loading
      uni.showLoading({
        title: '正在处理...'
      });

      // 创建订单-立即购买
      if (options.order_type === 'buyNow') {
        order_api.create({
          order_type: 'buyNow',
          address_id: that.need_address ? that.address.address_id : 0,
          item_id: options.item_id,
          goods_num: options.goods_num,
          spec_id: options.spec_id,
          coupon_id: that.selectCoupon.id,
          remark: that.remark,
          pay_way: that.pay_way,
          invoice_id: that.invoice_id
        }).then(res => {
          that.$u.toast(res.msg)
          if (res.code !== 0) {
            return;
          }
          that.pay_order(res)
        }).finally(() => {
          uni.hideLoading();
          // 解除按钮禁用
          that.disabled = false;
        })
      } else if (options.order_type === 'cart') {
        order_api.create({
          order_type: 'cart',
          address_id: that.need_address ? that.address.address_id : 0,
          cart_ids: options.cart_ids,
          coupon_id: that.selectCoupon.id,
          remark: that.remark,
          pay_way: that.pay_way,
          invoice_id: that.invoice_id
        }).then(res => {
          that.$u.toast(res.msg)
          if (res.code !== 0) {
            return;
          }
          that.pay_order(res)
        }).finally(() => {
          uni.hideLoading();
          // 解除按钮禁用
          that.disabled = false;
        })
      }
    },

    /**
     * 买家留言
     */
    bindRemark: function (e) {
      this.setData({
        remark: e.detail.value
      });
    },


    /**
     * 选择优惠券(弹出/隐藏)
     */
    togglePopupCoupon() {
      if (this.coupon_list.length > 0) {
        this.setData({
          showBottomPopup: !this.showBottomPopup
        });
      }
    },


    /**
     * 选择优惠券
     */
    selectCouponTap: function (e) {
      let dataset = e.currentTarget.dataset;
      let selectCoupon = this.coupon_list[dataset.index]
      //console.log(selectCoupon,this.order_pay_price)

      // 优惠券折扣金额
      let reducedPrice = selectCoupon.reduce_price;
      // 计算优惠后的价格
      let actualPayPrice = this.bcsub(this.order_pay_price, reducedPrice);
      // console.log('actualPayPrice', actualPayPrice)
      this.setData({
        selectCoupon: selectCoupon,
        actual_pay_price: actualPayPrice > 0 ? actualPayPrice : '0.01'
      });
      this.togglePopupCoupon();
    },

    /**
     * 不使用优惠券
     */
    doNotCouponTap: function () {
      this.setData({
        selectCoupon: {},
        actual_pay_price: this.order_pay_price
      });
      this.togglePopupCoupon();
    },

    /**
     * 数学运算相减
     */
    bcsub: function (arg1, arg2) {
      return (Number(arg1) - Number(arg2)).toFixed(2);
    }
  }
};
</script>
<style lang="scss" scoped>
@import 'checkout.scss';
</style>
